package auth

import (
	"backend/Service/redisService"
	"github.com/gin-gonic/gin"
	"strings"
)

func Auther() gin.HandlerFunc {
	return func(c *gin.Context) {
		url := c.Request.URL.String()
		get := c.Request.Header.Get("tk")
		if get == "" {
			get = c.Query("tk")
		}
		if strings.Index(url, "/teacher") == 0 {

			token, s := redisService.GetIdByToken(get)
			if !token || !strings.Contains(get, "t-") {
				c.Abort()
				c.String(401, "log first")
				return
			}
			c.Set("userId", s)
			c.Next()
		} else if strings.Index(url, "/open") == 0 {
			c.Next()
		} else {

			token, s := redisService.GetIdByToken(get)
			if !token {
				c.Abort()
				c.String(401, "log first")
				return
			}
			c.Set("userId", s)
			c.Next()
		}
	}
}
